Vue Js Dynamically Change Color,font size,background-color: In Vue.js, the v-bind:style
directive allows you to bind one or more CSS styles to an element’s style attribute. This can be useful for dynamically updating the styles of an element based on the component’s state or props. The value of the directive should be an object, where the keys are the CSS property names and the values are the corresponding values. In this tutorial, we will learn how to change the color, font size, and background colour of dynamic elements by clicking a button.
How to Vue Js dynamic change style (color, font size, background color)
In this example, you can change the styles of an element on click by using the v-on:click
the directive in conjunction with the v-bind:style
directive. For example, to change the color, font size, and background color style of a div
element when it is clicked: we can define the changeStyle
method, which updates the color, font size,bgColor
data property:
Vue Js change style on click
<div id="app">
<div v-bind:style="{ 'color': color, 'font-size': fontSize + 'px','background-color':bgColor }">Font Awesome
Icons</div><br>
<button @click="changeStyle">Change Style</button>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
color: 'red',
fontSize: '20',
bgColor: 'black'
}
},
methods: {
changeStyle() {
this.color = 'green';
this.fontSize = 25;
this.bgColor = 'orange'
}
}
});
</script>
Output of above example
Before changing style
After changing style